package com.bnyy.medicalHousekeeper.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.SpanUtils;
import com.bnyy.medicalHousekeeper.GlideHelper;
import com.bnyy.medicalHousekeeper.R;
import com.bnyy.medicalHousekeeper.base.BaseActivityImpl;
import com.bnyy.medicalHousekeeper.bean.Goods;
import com.bnyy.medicalHousekeeper.bean.Note;
import com.bnyy.medicalHousekeeper.bean.ServiceGoodsDetail;
import com.bnyy.medicalHousekeeper.bean.ShopInfo;
import com.bnyy.medicalHousekeeper.request.BaseObserverImpl;
import com.bnyy.medicalHousekeeper.request.RequestManager;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.youth.banner.Banner;
import com.youth.banner.adapter.BannerImageAdapter;
import com.youth.banner.holder.BannerImageHolder;
import com.youth.banner.listener.OnPageChangeListener;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.BindView;

/**
 * Author : 关炳鹏
 * Description :
 * Date : 2022/9/28
 **/
public class ServiceGoodsDetailActivity extends BaseActivityImpl {

    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.tv_indicator)
    TextView tvIndicator;
    @BindView(R.id.tv_goods_name)
    TextView tvGoodsName;
    @BindView(R.id.tag_flow_layout)
    TagFlowLayout tagFlowLayout;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.ll_item_container)
    LinearLayout llItemContainer;
    @BindView(R.id.ll_item_root)
    LinearLayout llItemRoot;
    @BindView(R.id.tv_share)
    TextView tvShare;

    private int goodsId;

    public static void show(Context context, int goodsId) {
        Intent intent = new Intent(context, ServiceGoodsDetailActivity.class);
        intent.putExtra("goodsId", goodsId);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_service_goods_detail;
    }

    @Override
    public boolean unuseRefreshLayout() {
        return true;
    }

    @Override
    public String getTitleStr() {
        return "商品详情";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setStatusBarColor(Color.WHITE);

        goodsId = getIntent().getIntExtra("goodsId", -1);
        if (goodsId == -1) {
            finish();
        } else {
            HashMap<String, Object> params = new HashMap<>();
            params.put("id", goodsId);

            requestManager.request(requestManager.mJavaRetrofitService.getServiceGoodsDetail(RequestManager.getJsonRequestBody(params)),
                    new BaseObserverImpl<ServiceGoodsDetail>(mContext) {
                        @Override
                        public void onSuccess(ServiceGoodsDetail serviceGoodsDetail) {
                            super.onSuccess(serviceGoodsDetail);
                            tvGoodsName.setText(serviceGoodsDetail.getName());

                            setTags(serviceGoodsDetail.getGoods_type(), serviceGoodsDetail.getTags());

                            setBanner(serviceGoodsDetail.getGoods_imgs());

                            setShopInfo(serviceGoodsDetail.getShop_info());

                            setItems(serviceGoodsDetail.getGoods_details());

                            setGoodsDetail(serviceGoodsDetail.getGoods_detail_text(), serviceGoodsDetail.getGoods_detail_imgs(), serviceGoodsDetail.getUse_items());

                            tvShare.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    ArticleListActivity.show(mContext, serviceGoodsDetail.getId(), serviceGoodsDetail.getGoods_type());
                                }
                            });
                        }
                    });
        }
    }

    private void setTags(int type, ArrayList<String> tags) {
        tagFlowLayout.setAdapter(new TagAdapter<String>(tags) {
            @Override
            public View getView(FlowLayout parent, int position, String s) {
                TextView tv = new TextView(mContext);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
                tv.setPadding(10, 5, 10, 5);
                tv.setTextColor(Color.parseColor(type == 1 ? "#41BE49" : "#FFA13D"));
                GradientDrawable bg = new GradientDrawable();
                bg.setCornerRadius(5);
                bg.setColor(Color.parseColor(type == 1 ? "#E8F6E7" : "#FFF9F2"));
                tv.setBackground(bg);
                tv.setText(s);
                return tv;
            }
        });
    }

    private void setShopInfo(ShopInfo shopInfo) {
        if (shopInfo != null) {
            tvShopName.setText(shopInfo.getName());
            tvAddress.setText(shopInfo.getAddr());
        }
    }

    private void setItems(ArrayList<ServiceGoodsDetail.Item> items) {
        if (items.size() > 0) {
            llItemRoot.setVisibility(View.VISIBLE);

            GradientDrawable bg = new GradientDrawable();
            bg.setCornerRadius(SizeUtils.dp2px(10));
            bg.setColors(new int[]{Color.parseColor("#FF9D53"), Color.parseColor("#FFD5B4")});
            bg.setOrientation(GradientDrawable.Orientation.TOP_BOTTOM);
            llItemRoot.setBackground(bg);

            for (int i = 0; i < items.size(); i++) {
                ServiceGoodsDetail.Item item = items.get(i);

                LinearLayout linearLayout = new LinearLayout(mContext);
                linearLayout.setGravity(Gravity.CENTER_VERTICAL);
                linearLayout.setOrientation(LinearLayout.HORIZONTAL);
                linearLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

                TextView tvItem = new TextView(mContext);
                tvItem.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                tvItem.setTextColor(ContextCompat.getColor(mContext, R.color.gray_text));

                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
                layoutParams.weight = 1;
                tvItem.setSingleLine(true);
                tvItem.setPadding(0, 0, SizeUtils.dp2px(12), 0);
                tvItem.setEllipsize(TextUtils.TruncateAt.END);
                tvItem.setLayoutParams(layoutParams);
                tvItem.setText(item.getContent());
                linearLayout.addView(tvItem);

                TextView tvCount = new TextView(mContext);
                tvCount.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                tvCount.setTextColor(ContextCompat.getColor(mContext, R.color.gray_text));
                tvCount.setText(item.getNumber() + "次");
                linearLayout.addView(tvCount);

                llItemContainer.addView(linearLayout);

                if (i != items.size() - 1) {
                    inflater.inflate(R.layout.divider_with_margin, llItemContainer, true);
                }
            }
        }
    }

    private void setBanner(ArrayList<String> goodsImages) {
        int width = ScreenUtils.getScreenWidth();
        banner.setLayoutParams(new RelativeLayout.LayoutParams(width, width / 15 * 13));
        banner.setAdapter(new BannerImageAdapter<String>(goodsImages) {
            @Override
            public void onBindView(BannerImageHolder holder, String data, int position, int size) {
                Glide.with(mContext).load(GlideHelper.getGlideUrl(data)).centerCrop().into(holder.imageView);
            }
        });

        banner.isAutoLoop(false);

        GradientDrawable bg = new GradientDrawable();
        bg.setColor(Color.parseColor("#40000000"));
        bg.setCornerRadius(360);

        tvIndicator.setBackground(bg);
        tvIndicator.setTextColor(Color.WHITE);
        tvIndicator.setText("1 / " + goodsImages.size());

        banner.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tvIndicator.setText((position + 1) + " / " + goodsImages.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void setGoodsDetail(String goodsDesc, ArrayList<String> goodsDetailImages, ArrayList<Note> notes) {
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(new RecyclerView.Adapter<RecyclerView.ViewHolder>() {

            int padding = SizeUtils.dp2px(12);
            int itemCount = goodsDetailImages.size() + 1 + (TextUtils.isEmpty(goodsDesc) ? 0 : 1);

            @Override
            public int getItemViewType(int position) {

                if (TextUtils.isEmpty(goodsDesc)) {
                    return position == getItemCount() - 1 ? 1 : 2;
                } else {
                    if (position == 0) {
                        return 0;
                    } else {
                        return position == getItemCount() - 1 ? 1 : 2;
                    }
                }
            }

            @NonNull
            @Override
            public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                if (viewType == 0) {
                    TextView tv = new TextView(mContext);
                    tv.setTextColor(ContextCompat.getColor(mContext, R.color.gray_text));
                    tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                    tv.setPadding(padding, padding, padding, padding);
                    tv.setLineSpacing(SizeUtils.dp2px(10), 1);
                    return new DescViewHolder(tv);
                } else if (viewType == 1) {
                    TextView tv = new TextView(mContext);
                    tv.setTextColor(ContextCompat.getColor(mContext, R.color.gray_text));
                    tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                    tv.setPadding(padding, padding, padding, padding);
                    tv.setLineSpacing(SizeUtils.dp2px(10), 1);
                    return new NoteViewHolder(tv);
                } else {
                    return new DetailImageViewHolder(new RelativeLayout(mContext));
                }
            }

            @Override
            public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
                if (holder instanceof DescViewHolder) {
                    ((DescViewHolder) holder).tv.setText(goodsDesc);
                } else if (holder instanceof DetailImageViewHolder) {
                    DetailImageViewHolder detailImageViewHolder = (DetailImageViewHolder) holder;
                    Glide.with(mContext)
                            .load(GlideHelper.getGlideUrl(goodsDetailImages.get(TextUtils.isEmpty(goodsDesc) ? position : position - 1)))
                            .into(new CustomTarget<Drawable>() {
                                @Override
                                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                    int minimumWidth = resource.getMinimumWidth();
                                    int minimumHeight = resource.getMinimumHeight();

                                    int screenWidth = ScreenUtils.getScreenWidth();


                                    int height = screenWidth * minimumHeight / minimumWidth;

                                    ImageView iv;

                                    if (detailImageViewHolder.rl.getChildCount() > 0) {
                                        iv = (ImageView) detailImageViewHolder.rl.getChildAt(0);
                                    } else {
                                        iv = new ImageView(mContext);
                                        detailImageViewHolder.rl.addView(iv);
                                    }
                                    iv.setLayoutParams(new RelativeLayout.LayoutParams(screenWidth, height));
                                    iv.setImageDrawable(resource);
                                }

                                @Override
                                public void onLoadCleared(@Nullable Drawable placeholder) {

                                }
                            });
                } else if (holder instanceof NoteViewHolder) {
                    NoteViewHolder noteViewHolder = (NoteViewHolder) holder;
                    SpanUtils spanUtils = SpanUtils.with(noteViewHolder.tv);
                    for (Note note : notes) {
                        String title = note.getTitle();
                        boolean b = title.contains("温馨提示");
                        spanUtils.append("●").setFontSize(10, true).setForegroundColor(Color.parseColor("#FF7026")).appendSpace(10)
                                .append(title);
                        if (b) {
                            spanUtils.setBold().appendLine();
                        }

                        spanUtils.append(note.getContent());
                        if (b) {
                            spanUtils.setForegroundColor(ContextCompat.getColor(mContext, R.color.gray_light));
                        }
                        spanUtils.appendLine();
                    }
                    spanUtils.create();
                }
            }

            @Override
            public int getItemCount() {
                return itemCount;
            }
        });
    }

    private static class DetailImageViewHolder extends RecyclerView.ViewHolder {

        RelativeLayout rl;

        public DetailImageViewHolder(@NonNull View itemView) {
            super(itemView);
            rl = (RelativeLayout) itemView;
        }
    }

    private static class NoteViewHolder extends RecyclerView.ViewHolder {

        TextView tv;

        public NoteViewHolder(@NonNull View itemView) {
            super(itemView);
            tv = (TextView) itemView;
        }
    }

    private static class DescViewHolder extends RecyclerView.ViewHolder {

        TextView tv;

        public DescViewHolder(@NonNull View itemView) {
            super(itemView);
            tv = (TextView) itemView;
        }
    }
}













































































